<?php

define("DB_HOST",		"localhost");
define("DB_USERNAME",	"cs411");
define("DB_PASSWORD",	"cs411");
define("DB_NAME",		"myparadise_db");

// Call this function before any database operation.
// This function will return a database connection.
function get_db_con()
{
	global $g_con;
	$g_con = mysqli_connect(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
	
	if (mysqli_connect_errno($g_con)) {
		echo "Failed to connect to MySQL: " . mysqli_connect_error();
	}
	
	return $g_con;
}

// Call this function right after you're done with
// database manipulation, i.e. query, insert, update, delete, etc.
function close_db_con()
{
	global $g_con;
	mysqli_close($g_con);
}

// This function will call the SELECT query, and return
// records as an array.
function select($con, $query)
{
	$records = array();
	
	$result = mysqli_query($con, $query);
	if ($result !== FALSE) {
		while($row = mysqli_fetch_array($result)) {
			array_push($records, $row);
		}
	}
	
	return $records;
}

// This function will call INSERT query, and return
// an auto-generated id of the record.
function insert($con, $query, $return_id = TRUE)
{
	$result = update($con, $query);
	
	if ($return_id === TRUE) {
		$result = mysqli_insert_id($con); 
	}
	
	return $result;
}

// This function will call UPDATE query, and return
// TRUE or FALSE
function update($con, $query)
{
	$result = mysqli_query($con, $query);
	return $result;	
}

// This function will call DELETE query, and return TRUE or FALSE
// depending on whether the deletion succeeded.
function delete($con, $query)
{
	$result = mysqli_query($con, $query);
	return $result;
}
